package com.tping.design.singleton.register;

import java.util.concurrent.*;

/**
 * @author xiai
 * @Date 2023/2/12 19:10
 * @Version 1.0
 */
public class UserPasswordSystemManager {

    /**
     * 单例对象
     */
    private static final UserPasswordSystemManager INSTANCE = new UserPasswordSystemManager();

    private UserPasswordSystemManager(){}

    public static UserPasswordSystemManager getInstance(){
        return INSTANCE;
    }

    /**
     * 自定义线程池
     */
    private static final ExecutorService threadPool = new ThreadPoolExecutor(
            1,
            Runtime.getRuntime().availableProcessors() * 2,
            60,
            TimeUnit.SECONDS,
            new SynchronousQueue<>(),
            new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r, "register-thread");
                    thread.setDaemon(true);
                    return thread;
                }
            });

    /**
     * 注册
     *
     * @param username
     * @param phoneNumber
     */
    public void register(String username, String phoneNumber){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                ThreadSpecificSecureRandom threadSpecificSecureRandom = ThreadSpecificSecureRandom.getInstance();
                StringBuffer buff = new StringBuffer();
                for (int i = 0; i < 6; i++) {
                    buff.append(threadSpecificSecureRandom.nextInt(10));
                }

                String initPassword = buff.toString();

                // 注册用户
                saveUser(username, phoneNumber, initPassword);
                // 发送短信
                sendMessage(username, phoneNumber, initPassword);
            }
        };

        threadPool.submit(runnable);
    }

    private void sendMessage(String username, String phoneNumber, String initPassword) {
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("登录账号：" + username + " ,手机号：" + phoneNumber + ", 初始化密码：" + initPassword);
    }

    private void saveUser(String username, String phoneNumber, String initPassword) {
        System.out.println("保证账号：" + username + " ,手机号：" + phoneNumber + ", 初始化密码：" + initPassword);
    }

}
